import json
import logging
from common import Authorization, CloudServiceS3, Response
from configuration import is_running_on_aws_lambda

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not is_running_on_aws_lambda():
    handler = logging.StreamHandler()
    # format the log
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    
def lambda_handler(event: dict, context):
    is_login, user_info = Authorization.get_user_info(event)
    if not is_login:
       return user_info
   
    query = event.get('queryStringParameters', {})
    method = event.get('requestContext', {}).get('http', {}).get('method', 'GET')
    body = event.get('body', {})
    try:
        body = json.loads(body)
    except:
        pass
    
    method_handler = {
        'GET': handle_get,
        'POST': handle_post,
        'PUT': handle_put,
        'DELETE': handle_delete,
    }
    
    return method_handler[method](query, user_info, body)

def handle_get(query: dict, user_info: dict, body: dict):
    path = query.get('path', '/')
    cloud_service = CloudServiceS3(user_info)
    
    try:
        if cloud_service.is_dir(path):
            return Response.build_success_response(cloud_service.list_current_structure(path))
        else:
            # 如果是文件，返回下载响应
            return cloud_service.get_file_source_by_path(path)
    except Exception as e:
        logger.error(f"获取文件失败: {e}")
        return Response.build_error_response(f"访问资源不存在", 404)

def handle_post(query: dict, user_info: dict, body: dict):
    """处理POST请求：上传文件或新建目录"""
    try:
        action = body.get('action', '')
        path = body.get('path', '/')
        name = body.get('name', '')

        cloud_service = CloudServiceS3(user_info)
        
        if action == 'create_dir':
            if not name:
                return Response.build_error_response("目录名不能为空", 400)
            # 新建目录
            cloud_service.create_dir(path, name)
            logger.info(f"创建目录成功: {path}/{name}")
            return Response.build_success_response({
                'message': '目录创建成功',
                'path': f"{path}/{name}"
            })
        
        elif action == 'upload_file':
            if not name:
                return Response.build_error_response("文件名不能为空", 400)
            # 上传文件
            file_content = body.get('file_content', '')
            file_encoding = body.get('file_encoding', 'utf-8')
            
            if not file_content:
                return Response.build_error_response("缺少文件内容", 400)
            
            # 判断是否为文本文件
            file_extension = ''
            if '.' in name:
                file_extension = name.split('.')[-1].lower()
            
            text_extensions = {'txt', 'md', 'json', 'xml', 'html', 'htm', 'css', 'js', 'py', 'java', 'cpp', 'c', 'php', 'rb', 'go', 'rs', 'sh', 'bat', 'ps1', 'ini', 'conf', 'log', 'csv'}
            
            if file_extension in text_extensions:
                # 文本文件，直接使用文本内容
                cloud_service.put_text_file(path, name, file_content, file_encoding)
            else:
                # 二进制文件，需要base64解码
                try:
                    import base64
                    binary_content = base64.b64decode(file_content)
                    cloud_service.put_file(path, name, binary_content)
                except Exception as e:
                    logger.error(f"文件解码失败: {e}")
                    return Response.build_error_response("文件内容格式错误", 400)
            
            logger.info(f"文件上传成功: {path}/{name}")
            return Response.build_success_response({
                'message': '文件上传成功',
                'path': f"{path}/{name}"
            })
        
        elif action == 'download_file':
            # 离线下载文件
            download_url = body.get('url', '')
            
            if not download_url:
                return Response.build_error_response("缺少下载链接", 400)
            
            try:
                logger.info(f"开始离线下载文件: {download_url}")
                # 执行离线下载，如果name为空则传递None
                custom_filename = name if name else None
                file_info = cloud_service.download_file_from_url(download_url, path, custom_filename)
                
                logger.info(f"离线下载成功: {file_info['filename']}")
                return Response.build_success_response({
                    'message': '文件下载成功',
                    'file_info': file_info
                })
                
            except Exception as e:
                logger.error(f"离线下载失败: {e}")
                return Response.build_error_response(f"下载失败: {str(e)}", 500)
        
        else:
            return Response.build_error_response("无效的操作类型，支持：create_dir, upload_file, download_file", 400)
            
    except Exception as e:
        logger.error(f"POST请求处理失败: {e}")
        return Response.build_error_response(f"操作失败: {str(e)}", 500)

def handle_put(query: dict, user_info: dict, body: dict):
    """处理PUT请求：重命名文件或目录"""
    try:
        action = body.get('action', '')
        old_path = body.get('old_path', '')
        new_path = body.get('new_path', '')
        
        if not old_path or not new_path:
            return Response.build_error_response("缺少必要参数：old_path 或 new_path", 400)
        
        if action != 'rename':
            return Response.build_error_response("无效的操作类型，支持：rename", 400)
        
        cloud_service = CloudServiceS3(user_info)
        
        # 重命名路径
        cloud_service.rename_path(old_path, new_path)
        logger.info(f"重命名成功: {old_path} -> {new_path}")
        
        return Response.build_success_response({
            'message': '重命名成功',
            'old_path': old_path,
            'new_path': new_path
        })
        
    except Exception as e:
        logger.error(f"PUT请求处理失败: {e}")
        return Response.build_error_response(f"重命名失败: {str(e)}", 500)

def handle_delete(query: dict, user_info: dict, body: dict):
    """处理DELETE请求：删除文件或目录"""
    try:
        action = body.get('action', '')
        path = body.get('path', '')
        
        if not path:
            return Response.build_error_response("缺少必要参数：path", 400)
        
        if action != 'delete':
            return Response.build_error_response("无效的操作类型，支持：delete", 400)
        
        cloud_service = CloudServiceS3(user_info)
        
        # 删除路径
        cloud_service.delete_path(path)
        logger.info(f"删除成功: {path}")
        
        return Response.build_success_response({
            'message': '删除成功',
            'path': path
        })
        
    except Exception as e:
        logger.error(f"DELETE请求处理失败: {e}")
        return Response.build_error_response(f"删除失败: {str(e)}", 500)